package com.chunfen.dubbo.protocol.dubbo;

import com.chunfen.dubbo.framework.Invocation;
import io.netty.channel.*;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.Callable;

public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable<Map<String, ? extends Serializable>>{

    private Invocation invocation = null;

    private ChannelHandlerContext serverChannel = null;

    private Map<String, ? extends Serializable> result = null;


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.serverChannel = ctx;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        this.result = (Map<String, ? extends Serializable>) msg;
    }

    public void setInvocation(Invocation invocation) {
        this.invocation =  invocation;
    }

    public Invocation getInvocation() {
        return invocation;
    }

    public ChannelHandlerContext getServerChannel() {
        return serverChannel;
    }

    public void setServerChannel(ChannelHandlerContext serverChannel) {
        this.serverChannel = serverChannel;
    }

    public Map<String, ? extends Serializable> getResult() {
        return result;
    }

    public void setResult(Map<String, ? extends Serializable> result) {
        this.result = result;
    }

    @Override
    public Map<String, ? extends Serializable> call() throws Exception {
        serverChannel.writeAndFlush(invocation).sync();
        return result;
    }
}
